<?php

namespace Beerus\Modules\BasicSetting\Actions;

use Doraemon\model\DecoCompany\DecoCompanyOperatorBind;
use Doraemon\model\DecoCompany\DecoCompanyOperatorBindLog;
use Doraemon\model\DecoCompanyAuth;
use Doraemon\model\DesignerOperatorBind\DesignerOperatorBind;
use Doraemon\model\DesignerOperatorBind\DesignerOperatorBindLog;
use Doraemon\model\Operator;
use Illuminate\Http\Request;
use Encore\Admin\Actions\RowAction;

class DecoCompanyOperatorTransfer extends RowAction
{
    public $name = '一键迁移装修公司';

    public function handle($id, Request $request) {
        $toOperatorId = $request->post('to_operator_id');
        $decoCompanyUids = $request->post('deco_company_uids');
        $toOperatorInfo = Operator::getOperatorInfoById($toOperatorId, Operator::OPERATOR_TYPE_DECO_COMPANY_BIND);
        if (!$toOperatorInfo) {
            return $this->response()->error('迁移到的运营不存在');
        }
        $where = [
            'operator_id' => $id,
        ];
        if ($decoCompanyUids) {
            $errUids = [];
            $designerUids = rtrim($decoCompanyUids, ',');
            $where['uid'] = explode(',', $designerUids);
            foreach ($where['uid'] as $decoCompanyUid) {
                if (!DecoCompanyOperatorBind::isExist($decoCompanyUid, $id)) {
                    $errUids[] = $decoCompanyUid;
                }
            }
            if ($errUids) {
                return $this->response()->error('一键迁移失败, 这些uid不存在' . implode(',', $errUids));
            }
        }
        $uid = !empty($decoCompanyUids) ? $where['uid'] : DecoCompanyAuth::getUidByAdminOperatorId($id);
        if (!DecoCompanyAuth::updateInfo($uid, ['admin_operator_id' => $toOperatorId])) {
            return $this->response()->error('一键迁移失败1');
        }
        if (!DecoCompanyOperatorBind::updateInfo(
            [
                'operator_id' => $toOperatorId,
                'admin_name' => $toOperatorInfo['operator_admin_name']
            ], $where)) {
            return $this->response()->error('一键迁移失败2');
        }
        $logData = [
            'uid' => 0,
            'operator_id' => $toOperatorId,
            'admin_name' => $toOperatorInfo['operator_admin_name'],
            'log' => $id . '一键迁移到' . $toOperatorId . ':涉及z装修公司有{' . ($decoCompanyUids??'全部') . '}',
            'op_time' => date('Y-m-d H:i:s')
        ];
        DecoCompanyOperatorBindLog::insert($logData);
        return $this->response()->success('一键迁移成功')->refresh();
    }

    public function retrieveModel(Request $request)
    {
        if (!$key = $request->get('_key')) {
            return false;
        }
        return $key;
    }

    public function form()
    {
        $this->hidden('from_operator_id')->value($this->row->id);
        $this->text('to_operator_id', '迁移到运营ID')->required();
        $this->text('deco_company_uids', '需要迁移的装修公司uid')
            ->help('请以英文逗号,分隔；若全部迁移请勿填写！');
    }
}
